<?php

class Utils
{

public static function change_extension($path,$newext)
{
	$l = strlen($path);
	$pos = -1;
	for($i = $l-1; $i > 0; $i--)
		if($path[$i] == '.')
		{
			$pos = $i;
			break;
		}
	if($pos == -1)
		return ($path . "." . $newext);
	else
		return (substr($path,0,$pos+1) . $newext);
}

public static function get_extension($path)
{
	$l = strlen($path);
	$pos = -1;
	for($i = $l-1; $i > 0; $i--)
		if($path[$i] == '.')
		{
			$pos = $i;
			break;
		}
	if($pos == -1)
		return "";
	else
		return substr($path,$pos,$l);
}

public static function get_thumbnail($srcPath)
{
	return Utils::change_extension($srcPath,"_thumb_.png");
}

public static function str_starts_with($str,$starts)
{
	return (strpos($str,$starts) == 0);
}

public static function str_ends_with($str,$ends)
{
	return (strrpos($str,$ends) == (strlen($str)-strlen($ends)));
}

public static function str_i_starts_with($str,$starts)
{
	return (stripos($str,$starts) == 0);
}

public static function str_i_ends_with($str,$ends)
{
	return (strripos($str,$ends) == (strlen($str)-strlen($ends)));
}

//Uppercase the first character of each word in a string
//ucwords(strtolower($string));
//heLLo! My WORLD! hi!! -> Hello! My World! Hi!!

public static function encode_quotes($textstr)
{
	$newtext = $textstr;
	$newtext = str_replace("%","%20",$newtext);
	$newtext = str_replace('"',"%22",$newtext);
	$newtext = str_replace("'","%21",$newtext);
	return $newtext;
}

public static function decode_quotes($textstr)
{
	$newtext = $textstr;
	$newtext = str_replace("%22",'"',$newtext);
	$newtext = str_replace("%21","'",$newtext);
	$newtext = str_replace("%20","%",$newtext);
	return $newtext;
}

public static function decode_quotes_for_html($textstr)
{
	return $textstr;
	/*$newtext = $textstr;
	$newtext = str_replace("%22",'"',$newtext);
	$newtext = str_replace("%21","'",$newtext);
	return htmlspecialchars($newtext,ENT_QUOTES);*/
}

//html entities for xml parsing
//*************************************************
// Generate a list of entity declarations from the HTML_ENTITIES set that PHP knows about to dump into the document
public static function htmlentities_entities()
{
	$output = "<!DOCTYPE html [\n";
	foreach (Utils::get_html_translation_table_CP1252(HTML_ENTITIES) as $k => $value)
	{
		$name = substr($value, 1, strlen($value) - 2);
		switch ($name)
		{
			// These ones we can skip because they're built into XML
			case 'gt':
			case 'lt':
			case 'quot':
			case 'apos':
			case 'amp': break;
			default: $output .= "<!ENTITY ".$name." \"&#".ord($k).";\"> ";
		}
	}
	$output .= "]>\n";
	return($output);
}

// ref: http://php.net/manual/en/function.get-html-translation-table.php#76564
public static function get_html_translation_table_CP1252($type)
{
	$trans = get_html_translation_table($type);
	$trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
	$trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
	$trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
	$trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
	$trans[chr(134)] = '&dagger;';    // Dagger
	$trans[chr(135)] = '&Dagger;';    // Double Dagger
	$trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
	$trans[chr(137)] = '&permil;';    // Per Mille Sign
	$trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
	$trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
	$trans[chr(140)] = '&OElig;';    // Latin Capital Ligature OE
	$trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
	$trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
	$trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
	$trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
	$trans[chr(149)] = '&bull;';    // Bullet
	$trans[chr(150)] = '&ndash;';    // En Dash
	$trans[chr(151)] = '&mdash;';    // Em Dash
	$trans[chr(152)] = '&tilde;';    // Small Tilde
	$trans[chr(153)] = '&trade;';    // Trade Mark Sign
	$trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
	$trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
	$trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
	$trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
	$trans['euro'] = '&euro;';    // euro currency symbol
	ksort($trans);
	return $trans;
}
//*************************************************

//quando si usa urlencode su unaa stringa codificata con utf8 possono esserci problemi
//allora utilizzare to_utf8(urlencode(str))
public static function to_utf8( $string )
{
// From http://w3.org/International/questions/qa-forms-utf-8.html
    if ( preg_match('%^(?:
      [\x09\x0A\x0D\x20-\x7E]            # ASCII
    | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
    | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
    | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
    | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
    | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
    | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
)*$%xs', $string) )
	{
		return $string;
	}
	else
	{
		return iconv( 'CP1252', 'UTF-8', $string);
	}
}

public static function decodeFromUTF8EncodedURL($str)
{
	return htmlentities(Utils::to_utf8(urldecode($str)), ENT_QUOTES, "UTF-8");
}

public static function decodeForHTMLFromUTF8EncodedURL($str)
{
	return Utils::to_utf8(urldecode($str));
}

public static function cleanSpecialChars($toClean)
{
	$normalizeChars = array(
    'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 
    'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 
    'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 
    'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 
    'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 
    'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 
    'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f'
	);
    $toClean     =     str_replace('&', '-and-', $toClean);
    //$toClean     =    trim(preg_replace('/[^\w\d_ -]/si', '', $toClean));//remove all illegal chars
    $toClean     =     str_replace(' ', '-', $toClean);
    
    return strtr($toClean, $normalizeChars);
}

//prende un filename qualsiasi ed elimina da esso ogni carattere che nn sia alfanumerico,
//o uno spazio, o uno di questi simboli "_.-"
public static function normalizeFilename($toClean)
{
	$newstr = preg_replace("/[^[:alnum:]\40_\.\-]/", "", $toClean);
	while(!(strpos($newstr,"  ") === FALSE))
		$newstr = str_replace("  "," ",$newstr);
	return $newstr;
}

public static function sendBack()
{
	echo("<script language='javascript'>sendBack();</script>");
}

public static function sendTo($url)
{
	echo("<script language='javascript'>document.location.href = '".$url."';</script>");
}

public static function alert($message)
{
	echo("<script language='javascript'>alert('".str_replace("'", "\\'", $message)."');</script>");
}

public static $monthNames = array(1 => "Gennaio", 2 => "Febbraio", 3 => "Marzo", 4 => "Aprile", 5 => "Maggio", 6 => "Giugno",
				7 => "Luglio", 8 => "Agosto", 9 => "Settembre", 10 => "Ottobre", 11 => "Novembre", 12 => "Dicembre");

public static function textualDateFormat($d)
{
	return (date("d",$d)." ".self::$monthNames[(int)date("m",$d)]." ".date("Y",$d));
}

public static function generalDateFormat($d)
{
	//return date("d/m/Y H:i:s",$d);
	return date("d/m/Y H:i",$d);
}

public static function shortDateFormat($d)
{
	return date("d/m/Y",$d);
}

public static function shortestDateFormat($d)
{
	return date("d/m/y",$d);
}

public static function shortTimeFormat($d)
{
	return date("H:i",$d);
}

public static function yesterday()
{
	return mktime(0,0,1,date('n'),date('j')-1,date('Y'));
}

public static function tomorrow()
{
	//return mktime(date('H'),date('i'),date('s'),date('n'),date('j')+1,date('Y'));
	return mktime(0,0,1,date('n'),date('j')+1,date('Y'));
}

public static function dateToMySqlFormat($date)
{
	return date("Y-m-d",$date);
}

public static function dateTimeToMySqlFormat($date)
{
	return date("Y-m-d H:i:s",$date);
}

public static function mySqlDateFormatToUnixTimestamp($dateStr)
{
	if($dateStr == "")
		return FALSE;
	$date = strtok($dateStr, " ");
	if($date === FALSE || $date == "")
		return FALSE;
	$time = strtok(" ");
	$year = strtok($date, "-");
	$month = strtok("-");
	$day = strtok("-");
	if(!$year || !$month || !$day || !checkdate($month, $day, $year))
		return FALSE;
	$sec = 0;
	$min = 0;
	$hour = 0;
	if($time !== FALSE || $time != "")
	{
		//è presente un tempo e mi vado a prendere le varie sue componenti
		$hour = strtok($date, ":");
		$min = strtok(":");
		$sec = strtok(":");
		//verifico che siano presenti ogn'una ed eseguo un cast in intero
		$hour = $hour === FALSE ? 0 : intval($hour);
		$min = $min === FALSE ? 0 : intval($min);
		$sec = $sec === FALSE ? 0 : intval($sec);
		//verifico che siano valori corretti che altrimenti porto a zero.
		$hour = $hour > 24 || $hour < 0 ? 0 : $hour;
		$min = $min > 60 || $min < 0 ? 0 : $min;
		$sec = $sec > 60 || $sec < 0 ? 0 : $sec;
	}
	return mktime($hour, $min, $sec, $month, $day, $year);
}

public static function addGet($startingUrl, $getToAdd)
{
	$resarr = parse_url($startingUrl,PHP_URL_QUERY);
	if($resarr == NULL)
		return $startingUrl.'?'.$getToAdd;
	else
	{
		if(strpos($startingUrl,'?'.$getToAdd) === FALSE && strpos($startingUrl,'&'.$getToAdd) === FALSE)
			return str_replace($resarr,$resarr.'&'.$getToAdd,$startingUrl);
		else
			return $startingUrl;
	}
}

public static function removeGet($startingUrl, $getToDel)
{
	$resarr = parse_url($startingUrl,PHP_URL_QUERY);
	if($resarr == NULL)
		return $startingUrl;
	$returnUrl = str_replace("&SigninError","",$startingUrl);
	$returnUrl = str_replace("SigninError","",$returnUrl);
	return $returnUrl;
}

public static function retrieveGet($startingUrl, $getToGet)
{
	$resarr = parse_url($startingUrl,PHP_URL_QUERY);
	if($resarr == NULL)
		return NULL;
	$spos = strpos($startingUrl,$getToGet."=");
	if($spos === FALSE)
		return NULL;
	$spos += strlen($getToGet."=");
	$fpos = strpos($startingUrl,"&",$spos);
	if($fpos === FALSE)
		return substr($startingUrl,$spos);
	else
		return substr($startingUrl,$spos,$fpos-$spos);
}

public static function SaveUploadedFile($tmppath,$initName,$dir)
{
	$finalfname = getcwd() . "/" . $dir . $initName;
	$finalpublicname = $dir . $initName;
	$rep_id = 1;
	while(file_exists($finalfname))
	{
		$finalfname = getcwd() . "/" . $dir . "r" . $rep_id . $initName;
		$finalpublicname = $dir . "r" . $rep_id . $initName;
		$rep_id++;
	}
	if(!move_uploaded_file($tmppath, $finalfname))
		return FALSE;
	else
		return $finalpublicname;
}

public static function insertIFrameByDocCode($name,$id,$width,$height,$style,$code)
{
	echo('
<iframe name="'.$name.'" id="'.$id.'" width="'.$width.'" height="'.$height.'" style="'.$style.'">
</iframe>
<script language="javascript" type="text/javascript">
var doc = AttivaFrame(\''.$id.'\');
doc.open();
');
$l = strlen($code);
for($i = 0; $i < $l; $i+=100)
{
	echo('doc.write(\''.str_replace("'","\\'",str_replace('\\','\\\\',substr($code,$i,100))).'\');
');
}
echo('doc.close();
</script>');
}

public static function sendHTMLMail($from, $to, $subject, $HTMLText, $replyto = "")
{
	$replyto_head = "";
	if($replyto != NULL && $replyto != "")
		$replyto_head = 'Reply-To: '.$replyto."\r\n";
	return mail($to,$subject,$HTMLText,"MIME-Version: 1.0\r\nContent-type: text/html; charset=iso-8859-1\r\nFrom: ".$from."\r\n".$replyto_head."X-Mailer: PHP/" . phpversion());
}

public static function makeClickableLinks($text)
{
	$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text);
	$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2">\\2</a>', $text);
	$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '<a href="mailto:\\1">\\1</a>', $text);
	return $text;
}

public static function formatPlainDescriptionText($text)
{
	return /*str_replace("\n","<br />",$text);*/str_replace("\n","<br />",Utils::makeClickableLinks($text));
}

public static function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

public static function httpPost($host, $path, $data)
{
	// esempio $data = "id=5&pippo=aaa";
	$fp = @fsockopen($host, 80);
	if(!$fp)
		return FALSE;
	fputs($fp, "POST " . $path . " HTTP/1.0\r\n");
	fputs($fp, "Host: " . $host . "\r\n");
	fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
	fputs($fp, "Content-length: " . strlen($data) . "\r\n");
	fputs($fp, "\r\n");
	fputs($fp, $data."\r\n");
	fputs($fp, "\r\n");
	$tmp_headers = "";
	while ($str = trim(fgets($fp, 4096)))
		$tmp_headers .= $str."\n";
	$tmp_body = "";
	while (!feof($fp))
		$tmp_body .= fgets($fp, 4096);
	fclose($fp);

	// ritorna la pagina
	return $tmp_headers.$tmp_body;
}

public static function httpGet($host, $path, $data)
{
	// esempio $data = "id=5&pippo=aaa";
	$fp = @fsockopen($host, 80);
	if(!$fp)
		return FALSE;
	fputs($fp, "GET " . $path . " HTTP/1.0\r\n");
	fputs($fp, "Host: " . $host . "\r\n");
	fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
	fputs($fp, "Content-length: " . strlen($data) . "\r\n");
	fputs($fp, "\r\n");
	fputs($fp, $data."\r\n");
	fputs($fp, "\r\n");
	$tmp_headers = "";
	while ($str = trim(fgets($fp, 4096)))
		$tmp_headers .= $str."\n";
	$tmp_body = "";
	while (!feof($fp))
		$tmp_body .= fgets($fp, 4096);
	fclose($fp);

	// ritorna la pagina
	return $tmp_headers.$tmp_body;
}

public static function downloadFile ($url, $path)
{
	$res = true;
	$newfname = $path;
	$file = fopen ($url, "rb");
	if ($file)
	{
		$newf = fopen ($newfname, "wb");
		if ($newf)
		{
			while(!feof($file))
			{
				fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
			}
		}
		else
			$res = false;
	}
	else
		$res = false;
	if ($file)
		fclose($file);
	if ($newf)
		fclose($newf);
	return $res;
}

public static function downloadSmallFile ($src_url, $dest_path)
{
	$f = file_get_contents($src_url);
	if($f != FALSE)
		return file_put_contents($dest_path, $f);
	else
		return FALSE;
}

// recursively remove a directory
public static function rrmdir($dir)
{
    foreach(glob($dir . '/*') as $file)
	{
        if(is_dir($file))
            self::rrmdir($file);
        else
            unlink($file);
    }
    rmdir($dir);
}

const CLIENT_DEVICE_DESKTOP = 0;
const CLIENT_DEVICE_TABLET = 1;
const CLIENT_DEVICE_MOBILE = 2;

public static function getDeviceType()
{
	$tablet_browser = 0;
	$mobile_browser = 0;

	if (preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
		$tablet_browser++;
	}

	if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
		$mobile_browser++;
	}

	if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
		$mobile_browser++;
	}

	$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
	$mobile_agents = array(
		'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
		'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
		'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
		'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
		'newt','noki','palm','pana','pant','phil','play','port','prox',
		'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
		'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
		'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
		'wapr','webc','winw','winw','xda ','xda-');

	if (in_array($mobile_ua,$mobile_agents)) {
		$mobile_browser++;
	}

	if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'opera mini') > 0) {
		$mobile_browser++;
		//Check for tablets on opera mini alternative headers
		$stock_ua = strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?$_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:(isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?$_SERVER['HTTP_DEVICE_STOCK_UA']:''));
		if (preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)) {
		  $tablet_browser++;
		}
	}
	
	if ($tablet_browser > 0)
		return self::CLIENT_DEVICE_TABLET;
	else if ($mobile_browser > 0)
		return self::CLIENT_DEVICE_MOBILE;
	else
		return self::CLIENT_DEVICE_DESKTOP;
}

}

?>
